package org.jeecg.modules.wlhy.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.exception.MyException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainVehicle;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainVehicleService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerAdmin;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerCompany;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerUser;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAdminService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerCompanyService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerUserService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserUtil {
    @Autowired
    ISysUserService sysUserService;

    @Autowired
    private IHyCustomerService hyCustomerService;

    @Autowired
    private IHySettingService hySettingService;

    @Autowired
    private IHyVehicleService vehicleService;

    @Autowired
    private IHyCustomerUserService hyCustomerUserService;

    @Autowired
    private IHySettingService settingService;

    @Autowired
    private IHyCustomerAdminService hyCustomerAdminService;

    @Autowired private IHyCustomerCompanyService hyCustomerCompanyService;
    @Autowired private IHyCompanyService hyCompanyService;
    @Autowired private IHyDriverService hyDriverService;


    @Value(value="${customer.roleid}")
    private String customerRoleID;

    @Autowired
    private IHyCaptainService captainService;

    @Autowired
    private IHyCaptainVehicleService hyCaptainVehicleService;

    @Autowired private IHyDriverVehicleService hyDriverVehicleService;

    public static HttpServletRequest getRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpSession session = request.getSession();
        return  request;
    }

    /**
     * 获取当前登陆人
     * @return
     */
    private SysUser getUser(HttpServletRequest req) {
        String tokenHeader = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(tokenHeader);
        SysUser user = sysUserService.getUserByName(username);
        if(user==null){
            throw new JeecgBootException("未获取到用户信息");
        }
        return user;
    }

    public  SysUser getUser() {
        HttpServletRequest request = getRequest();
        return  getUser(request);
    }


    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getUserNameByToken(HttpServletRequest request) throws JeecgBootException {
        String accessToken = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = getUsername(accessToken);
        if (oConvertUtils.isEmpty(username)) {
            throw new JeecgBootException("未获取到用户");
        }
        return username;
    }
    public static String getUserNameByToken() throws JeecgBootException {
        HttpServletRequest request = getRequest();
        return getUserNameByToken(request);
    }

    /**
     * 获取登陆用户信息
     * @return
     */
    public  static LoginUser getLoginUser(){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser == null){
            throw new JeecgBootException("未获取到用户登陆信息");
        }
        return loginUser;
    }

    public static void main(String[] args) {
//       String username = getUsername("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDcwNjIzNTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.ZLYWb_ewE8gUKF4ms5CyrHwH9vRHgLslXWFuHjLP7Dk");
//        System.out.println(username);
        System.out.println(PasswordUtil.encrypt("8B9xFR9FREJc8td7", "123456", "ogjzF0P8"));
    }

    public boolean isSys(){
        LoginUser loginUser = getLoginUser();
        String uType = loginUser.getUType();
        return UserTypeEnum.管理员.getCode().equals(uType);
    }

    /**
     * 是否是业务管理员，负责处理指定货主的业务数据
     */
    public boolean isCustomerAdmin(){
        LoginUser loginUser = getLoginUser();
        String uType = loginUser.getUType();
        return UserTypeEnum.业务管理员.getCode().equals(uType);
    }

    /**
     * 获取业务管理员绑定货主的id列表
     */
    public List<String> getCustomerAdminRelationIdList() {
        LoginUser loginUser = getLoginUser();
        String id = loginUser.getId();
        List<HyCustomerAdmin> customerAdminList = this.hyCustomerAdminService.list(new LambdaQueryWrapper<HyCustomerAdmin>().eq(HyCustomerAdmin::getUserId, id));
        if (CollUtil.isEmpty(customerAdminList)) {
            throw new JeecgBootException("当前业务员未关联货主");
        }

        List<String> customerIds = customerAdminList.stream().map(HyCustomerAdmin::getCustomerId).collect(Collectors.toList());
        return customerIds;
    }

    /**
     * 判断已登陆用户的信息，是否货主
     * @return
     */
    public HyCustomer getCustomer() {
        LoginUser loginUser = getLoginUser();

        String uType = loginUser.getUType();

        HyCustomer customer = null;
        if ("2".equals(uType)) {
            customer =  hyCustomerService.getCustomerByUserId(loginUser.getId());
            if(customer == null){
                log.error("货主信息不存在{}", JSONUtil.toJsonStr(loginUser));
                throw new MyException("货主信息不存在");
            }
            if("0".equals(customer.getIzUsed())){
                throw new MyException("账号已停用");
            }
            if(!"2".equals(customer.getExamineStatus())){
                throw new MyException("账号正在审核中");
            }
        }
        if ("3".equals(uType)) {
            HyCustomerUser customerUser = hyCustomerUserService.getOne(new QueryWrapper<HyCustomerUser>().eq("user_id", loginUser.getId()));
            if(customerUser == null){
                throw new MyException("货主子账号信息不存在");
            }
            if("0".equals(customerUser.getIzUsed())){
                throw new MyException("账号已停用");
            }
            customer =  hyCustomerService.getById(customerUser.getCustomerId());
            if(customer == null){
                throw new MyException("货主信息不存在");
            }
            if("0".equals(customer.getIzUsed())){
                throw new MyException("账号已停用");
            }
            if(!"2".equals(customer.getExamineStatus())){
                throw new MyException("账号正在审核中");
            }
        }
        return customer;
    }

    /**
     * 判断已登陆用户的信息，是否货主
     * @return
     */
    public String getCustomerById() {
        LoginUser loginUser = getLoginUser();

        String uType = loginUser.getUType();

        HyCustomer customer = null;
        if ("2".equals(uType)) {
            customer =  hyCustomerService.getCustomerByUserId(loginUser.getId());
            if(customer == null){
                throw new MyException("货主信息不存在");
            }
            if("0".equals(customer.getIzUsed())){
                throw new MyException("账号已停用");
            }
            if(!"2".equals(customer.getExamineStatus())){
                throw new MyException("账号正在审核中");
            }
        }
        if ("3".equals(uType)) {
            HyCustomerUser customerUser = hyCustomerUserService.getOne(new QueryWrapper<HyCustomerUser>().eq("user_id", loginUser.getId()));
            if(customerUser == null){
                throw new MyException("货主子账号信息不存在");
            }
            if("0".equals(customerUser.getIzUsed())){
                throw new MyException("账号已停用");
            }
            customer =  hyCustomerService.getById(customerUser.getCustomerId());
            if(customer == null){
                throw new MyException("货主信息不存在");
            }
            if("0".equals(customer.getIzUsed())){
                throw new MyException("账号已停用");
            }
            if(!"2".equals(customer.getExamineStatus())){
                throw new MyException("账号正在审核中");
            }
        }
        if(customer!=null){
            return customer.getId();
        }else{
            return null;

        }
    }
    //获取货主签约的公司信息
    public HyCompany getSelCompany(String customerId) {

        if(StringUtils.isEmpty(customerId)){
            throw new MyException("货主信息不存在");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(customerId);
        if(customerCompany==null){
            throw new MyException("未找到货主签约信息");
        }
        HyCompany selCompany = hyCompanyService.getById(customerCompany.getCompanyId());
        if(selCompany == null){
            throw new MyException("分公司信息不存在");
        }
        return selCompany;
    }
    public HyCustomer getCustomerById(String customerId){
        return  hyCustomerService.getById(customerId);
    }

    //获取货主签约信息
    public HyCustomerCompany getCustomerCompany(String customerId) {
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(customerId);
        if(customerCompany==null){
            throw new MyException("未找到货主签约信息");
        }
        return  customerCompany;
    }

    /**
     * 用户登陆时，判断用户角色  1 系统管理员 2 货主角色
     * @param sysUser
     * @param result
     */
    public HyCustomer CheckUserRole(SysUser sysUser, Result<JSONObject> result) {
        result.getResult().put("userType","1");//默认系统用户
        result.getResult().put("cid","");

        String uType = sysUser.getUType();
        HyCustomer customer = null;
        if ("2".equals(uType)) {
            customer = hyCustomerService.getCustomerByUserId(sysUser.getId());
            if (customer != null) {
                if ("0".equals(customer.getIzUsed())) {
                    throw new JeecgBootException("账号已停用");
                }
                if (!"2".equals(customer.getExamineStatus())) {
                    throw new JeecgBootException("账号正在审核中");
                }
                result.getResult().put("userType", "2");
                result.getResult().put("cid", customer.getId());
            }
        }
        if ("3".equals(uType)) {
            HyCustomerUser customerUser = hyCustomerUserService.getOne(new QueryWrapper<HyCustomerUser>().eq("user_id", sysUser.getId()));
            if(customerUser == null){
                throw new JeecgBootException("货主子账号信息不存在");
            }
            if("0".equals(customerUser.getIzUsed())){
                throw new JeecgBootException("账号已停用");
            }
            customer =  hyCustomerService.getById(customerUser.getCustomerId());
            if(customer == null){
                throw new JeecgBootException("货主信息不存在");
            }
            if("0".equals(customer.getIzUsed())){
                throw new JeecgBootException("账号已停用");
            }
            if(!"2".equals(customer.getExamineStatus())){
                throw new JeecgBootException("账号正在审核中");
            }
            result.getResult().put("userType","3");
            result.getResult().put("cid",customer.getId());
        }

        return  customer;
    }

    public HyDriver getDriver(){
        LoginUser loginUser = getLoginUser();
        String uType = loginUser.getUType();
        if (!"4".equals(uType)) {
            throw new JeecgBootException("不是司机账号");
        }
        HyDriver driver = hyDriverService.getHyDriverByUserId(loginUser.getId());
        if (driver == null) {
            throw new JeecgBootException("未获取到司机信息");
        }

//        if("0".equals(driver.getIzUsed())){
//            throw new MyException("账号已停用");
//        }
//        if(!"2".equals(driver.getExamineStatus())){
//            throw new JeecgBootException("账号正在审核中");
//        }
        //众汇添加开关校验
        HySetting hySetting = settingService.getByTag("checkValidDriver");
        if (hySetting!=null&&hySetting.getData().equals("1")){
            Result result = hyDriverService.checkValidDriver(driver);
            if (!result.isSuccess()){
                driver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
                driver.setExaminRemark("驾驶证信息已经过期，上传资料重新审核。");
                hyDriverService.updateById(driver);
            }

        }
        /*if (ObjectUtil.isEmpty(driver.getValidPeriodTo()) || driver.getValidPeriodTo().before(new Date())) {
            driver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
            driver.setExaminRemark("驾驶证信息已经过期，上传资料重新审核。");
            hyDriverService.updateById(driver);
        }*/
        return driver;
    }
    /**
     * 承运商角色获取司机id列表
     * @return
     */
    public List<String> getDriverList() {
        if (getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
            HyCaptain captain = captainService.getOne(new QueryWrapper<HyCaptain>().eq("user_id", getLoginUser().getId()));
            if (captain==null){
                throw new JeecgBootException("未获取到承运商信息");
            }
            List<HyCaptainVehicle> carriers = hyCaptainVehicleService.list(new QueryWrapper<HyCaptainVehicle>().eq("user_id", getLoginUser().getId()));
            //根据关联表获取绑定的车辆信息
            List<String> vehicleIdList = carriers.stream().map(HyCaptainVehicle::getVehicleId).collect(Collectors.toList());
            //根据车辆信息获取所绑定的司机信息
            List<String> driverList = new ArrayList<>();
            for (String vehicleId : vehicleIdList) {
                driverList.addAll(hyDriverVehicleService.getDriverIdListByVehicleId(vehicleId));
            }
            return driverList;
        }else {
            throw new JeecgBootException("角色不正确，请查看角色信息");
        }

    }
    /**
     * 是否是承运商
     * @return
     */
    public boolean isCaptain() {
        return getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode());
    }

    /**
     * 根据承运商用户id获取车辆id列表
     */
    public List<String> getHyVehicleIdList() {
        LoginUser loginUser = getLoginUser();
        if (!loginUser.getUType().equals(UserTypeEnum.承运商.getCode())) {
            throw new JeecgBootException("角色不正确，请查看角色信息");
        }
        HyCaptain captain = captainService.getOne(new QueryWrapper<HyCaptain>().eq("user_id", loginUser.getId()));
        if (captain == null) {
            throw new JeecgBootException("未获取到承运商信息");
        }
        List<HyCaptainVehicle> carriers = hyCaptainVehicleService.list(new QueryWrapper<HyCaptainVehicle>().eq("user_id", loginUser.getId()));
        // 根据关联表获取绑定的车辆信息
        List<String> vehicleIdList = carriers.stream().map(HyCaptainVehicle::getVehicleId).collect(Collectors.toList());
        return vehicleIdList;
    }

    /**
     * 是否是承运商
     * @return
     */
    public HyCaptain getHyCaptain() {
        LoginUser loginUser = getLoginUser();
        if (!loginUser.getUType().equals(UserTypeEnum.承运商.getCode())) {
            throw new JeecgBootException("角色不正确，请查看角色信息");
        }
        HyCaptain captain = captainService.getOne(new QueryWrapper<HyCaptain>().eq("user_id", loginUser.getId()));
        if (captain == null) {
            throw new JeecgBootException("未获取到承运商信息");
        }
        return  captain;
    }
}
